package annotation.reflect;

import java.lang.annotation.*;
import java.lang.reflect.Field;

public class ReflectAnnotation {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class sClass = Class.forName("annotation.reflect.StudentObject");

        //通过反射获得注解
        Annotation[] annotations = sClass.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获得注解value的值
        TableName tableName = (TableName)sClass.getAnnotation(TableName.class);
        String value = tableName.value();
        System.out.println(value);

        //获得类指定的注解
        Field field = sClass.getDeclaredField("name");
        FieldName annotation = field.getAnnotation(FieldName.class);
        System.out.println(annotation.columnName());

        Annotation[] annotationsByType = sClass.getAnnotationsByType(TableName.class);
        for (Annotation annotationType : annotationsByType) {
            System.out.println(annotationType);
        }
    }
}

@TableName("db_student")
class StudentObject {

    @FieldName(columnName = "db_id",TypeName = "int",length = 16)
    private int id;
    @FieldName(columnName = "db_age",TypeName = "int",length = 16)
    private int age;
    @FieldName(columnName = "db_name",TypeName = "varchar",length = 8)
    private String name;

    public StudentObject(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public StudentObject() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "StudentObject{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

//类名->表名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName {
    String value();
}

//属性->字段的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldName {
    String columnName();
    String TypeName();
    int length();
}